package com.dragon.logical.service.finance.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.logical.service.customer.CustomerService;
import com.dragon.logical.service.finance.IReimbursementService;
import com.dragon.repository.entity.AddPageData;
import com.dragon.repository.entity.Expenses;
import com.dragon.repository.entity.OtherFile;
import com.dragon.repository.entity.Reimbursement;
import com.dragon.repository.mapper.ExpensesMapper;
import com.dragon.repository.mapper.OtherFileMapper;
import com.dragon.repository.mapper.ReimbursementMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报销申请表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-07-03
 */
@Service
public class ReimbursementServiceImpl extends ServiceImpl<ReimbursementMapper, Reimbursement> implements IReimbursementService {

    @Autowired
    ReimbursementMapper mapper;
    @Autowired
    OtherFileMapper otherFileMapper;
    @Autowired
    CustomerService customerService;
    @Autowired
    ExpensesMapper expensesMapper;

    @Override
    public Page<Reimbursement> reimburseList(Integer page, Integer limit, String search, Integer status, Integer paymentStatus, String startTime, String endTime) {
        Page<Reimbursement> rePage = new Page<>(page, limit);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<Reimbursement> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(startTime) || StrUtil.isNotEmpty(endTime)) {
            if (StrUtil.isEmpty(endTime)) {
                endTime = DateUtil.date().toString();
            }
            if (StrUtil.isEmpty(startTime)) {
                startTime = "1999-01-01";
            }
            try {
                df.parse(startTime);
                df.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        wrapper.lambda().like(StrUtil.isNotBlank(search),Reimbursement::getReimbursementName,search)
                .eq(status!=null,Reimbursement::getStatus,status)
                .eq(paymentStatus!=null,Reimbursement::getPaymentStatus,paymentStatus)
                .ge(StrUtil.isNotBlank(startTime), Reimbursement::getCreateTime, startTime)
                .le(StrUtil.isNotBlank(endTime), Reimbursement::getCreateTime, endTime)
                .orderByDesc(Reimbursement::getCreateTime);
        Page<Reimbursement> reimbursementPage = mapper.selectListBySearch(rePage,wrapper);
        return reimbursementPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AddPageData addReimburse(Reimbursement reimbursement){
        reimbursement.setStatus(0);
        reimbursement.setCreateTime(DateUtil.date());
        mapper.insert(reimbursement);
        List<OtherFile> otherFiles = reimbursement.getOtherFiles();
        if (otherFiles != null || otherFiles.size() != 0){
            for (OtherFile otherFile : otherFiles) {
                otherFile.setStreamType(8);
                otherFile.setCorrelationId(reimbursement.getId());
                otherFileMapper.insert(otherFile);
            }
        }

        AddPageData addPageData = new AddPageData();
        addPageData.setAdminId(reimbursement.getAdminId());
        addPageData.setCorrelationId(reimbursement.getId());
        addPageData.setWorkflowJson(reimbursement.getWorkflowJsonList());
        addPageData.setStreamType(8);
        addPageData.setTitle(reimbursement.getReimbursementName());
        addPageData.setExempt(reimbursement.getExempt()==null?0:1);
        return addPageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReimburse(Reimbursement reimbursement){
        Reimbursement reimburse = mapper.selectById(reimbursement.getId());
        if (reimburse == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        reimburse.setUpdateTime(DateUtil.date());
        mapper.updateById(reimbursement);

        List<OtherFile> otherFiles = reimbursement.getOtherFiles();
        if (otherFiles != null) {
            QueryWrapper<OtherFile> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(OtherFile::getCorrelationId, reimbursement.getId()).eq(OtherFile::getStreamType,8);
            for (OtherFile otherFile: otherFiles) {
                otherFileMapper.update(otherFile,wrapper);
            }
        }
    }

    @Override
    public void reimbursePayment(Reimbursement reimbursement){
        Reimbursement reimburse = mapper.selectById(reimbursement.getId());
        if (reimburse == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        reimbursement.setPaymentStatus(1);
        mapper.updateById(reimbursement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteReimburse(Integer id){
        if (mapper.selectById(id).getStatus() == 3){
            throw new CustomException(ResultCode.REIMBURSEMENT_STATUS_THREE);
        }
        customerService.deleteThorough(8,id);
        mapper.deleteById(id);
        otherFileMapper.delete(new QueryWrapper<OtherFile>().lambda().eq(OtherFile::getCorrelationId, id).eq(OtherFile::getStreamType,8));
    }

    @Override
    public Reimbursement selectInfoById(Integer id){
        Reimbursement reimbursement = mapper.selectByReimburId(id);
        //单据类型
        String expensesName = expensesMapper.selectNameById(reimbursement.getReimburseType());
        reimbursement.setExpensesName(expensesName);
        //查询附件 8 加主表id
        QueryWrapper<OtherFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OtherFile::getCorrelationId, reimbursement.getId()).eq(OtherFile::getStreamType,8);
        List<OtherFile> list = otherFileMapper.selectList(wrapper);
        if (list != null){
            reimbursement.setOtherFiles(list);
        }

        return reimbursement;
    }

    @Override
    public Map<String,Object> selectListStatistics(){
        return mapper.selectListStatistics();
    }

    @Override
    public List<Expenses> reimburseTypePercentage(String time) {
        if (StrUtil.isBlank(time)){
            time = DateUtil.format(DateUtil.date(),"yyyy");
        }
        return mapper.reimburseTypePercentage(time);
    }

    @Override
    public LinkedHashMap<String, Object> reimburseMonthlyStatistics(String time) {
        if (StrUtil.isBlank(time)){
            time = DateUtil.format(DateUtil.date(),"yyyy");
        }
        return mapper.reimburseMonthlyStatistics(time);
    }
}
